use pyo3::prelude::*;

#[pyfunction]
fn option_finance_board_py(symbol: &str, end_month: &str) -> PyResult<String> {
    use akoption::types::{EndMonth, FinanceSymbol};
    let sym = match symbol.to_lowercase().as_str() {
        "sse50etf" => FinanceSymbol::Sse50Etf,
        "sse300etf" => FinanceSymbol::Sse300Etf,
        "sse500etf" => FinanceSymbol::Sse500Etf,
        "ssekc50etf" => FinanceSymbol::SseKc50Etf,
        "ssekc50etfyfd" => FinanceSymbol::SseKc50EtfYfd,
        "szse300etf" => FinanceSymbol::Szse300Etf,
        "cffex-io" => FinanceSymbol::CffexIO,
        "cffex-mo" => FinanceSymbol::CffexMO,
        "cffex-ho" => FinanceSymbol::CffexHO,
        _ => FinanceSymbol::Sse50Etf,
    };
    let end = EndMonth::new(end_month);
    let rt = tokio::runtime::Runtime::new().map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("runtime error: {}", e)))?;
    let data = rt.block_on(akoption::option_finance_board(sym, end))
        .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("fetch error: {}", e)))?;
    Ok(serde_json::to_string(&data).unwrap_or_else(|_| "[]".to_string()))
}

#[pyfunction]
fn option_current_em_py() -> PyResult<String> {
    let rt = tokio::runtime::Runtime::new().map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("runtime error: {}", e)))?;
    let data = rt.block_on(akoption::option_current_em())
        .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("fetch error: {}", e)))?;
    Ok(serde_json::to_string(&data).unwrap_or_else(|_| "[]".to_string()))
}

#[pyfunction]
fn option_finance_sse_underlying_py(symbol: &str) -> PyResult<String> {
    use akoption::types::SseUnderlying;
    let sym = match symbol.to_lowercase().as_str() {
        "huaxia50" | "华夏50" => SseUnderlying::HuaXia50,
        "huatai300" | "华泰300" => SseUnderlying::HuaTai300,
        "nanfang500" | "南方500" => SseUnderlying::NanFang500,
        "kechuang50" | "科创50" => SseUnderlying::KeChuang50,
        "kechuang50yfd" | "科创50yfd" => SseUnderlying::KeChuang50Yfd,
        _ => SseUnderlying::HuaXia50,
    };
    let rt = tokio::runtime::Runtime::new().map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("runtime error: {}", e)))?;
    let data = rt.block_on(akoption::option_finance_sse_underlying(sym))
        .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("fetch error: {}", e)))?;
    Ok(serde_json::to_string(&data).unwrap_or_else(|_| "{}".to_string()))
}

#[pymodule]
fn akoption_py(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(option_finance_board_py, m)?)?;
    m.add_function(wrap_pyfunction!(option_current_em_py, m)?)?;
    m.add_function(wrap_pyfunction!(option_finance_sse_underlying_py, m)?)?;
    Ok(())
}
